from urllib.parse import urlencode

import requests
from requests.cookies import RequestsCookieJar

#header 伪装浏览器设置
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Accept-Encoding': 'gzip, deflate, br',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Host': 'www.farpop.com',
        'X-Real-IP':'225.58.45.24',
        'X-Forwarded-For':'8.8.8.8',
        'Connection': 'keep-alive',
        'Cookie':''
}

#1-----------用Get 获取 网站信息
#为请求建立一个会话，保持状态，以后的url都用这个session来get post
session.get()里边不能直接写入cookie参数，把cookie写入到header直接请求
#session 是一个会话，他可以获得现在的cookie headers
session = requests.session()
#给会话添加headers ，不用每次都带上headers了
session.headers=headers
#会话请求 一个url，方式get ，https解除访问屏蔽verify=False
#html 是会话请求的结果，它可以获得当前的网页内容html.text
html.encoding = 'utf-8'

# cookie的设置，生成cooki
cookies = dict(cookies_are='working')

#2-----------POST登录，postData是form表单内容
#设置post提交格式
postData = {'ecmsfrom':'','enews': 'login','tobind': '0','username':' shenhuawade','password': '1987wade','lifetime': '99990',
    'Submit': '(unable to decode value)'}

html1 = session.post(url='https://www.farpop.com/e/member/doaction.php',data=postData, verify=False)
print(session.cookies.get_dict())

#3----------Post发帖
datas = {
    'spacename': 'ni shi一个大好人',
    'spacegg': 'ni shi一个大好人123',
    'Submit': '(unable to decode value)',
    'enews': 'DoSetSpace'
}
url = 'https://www.farpop.com/e/member/mspace/index.php'
#将form提交数据转换成网页对应合适，本网站的格式gb2312，然后不要用datas直接放到会话请求里边，用转换好的格式data_gb2312来请求
data_gb2312 = urlencode(datas, encoding='gb2312')
html2 = session.post(url=url,data=data_gb2312,verify=False,error = 'ignore')
print(html2.text)
print(session.cookies.get_dict())

url = 'https://www.farpop.com/e/space/?userid=10388587'
html3 = session.get(url=url, verify=False,error = 'ignore')
#设置获取session请求后的cookie
print(session.cookies.get_dict())
print(html3.text)